package com.hurt.competition.player.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hurt.competition.admin.dto.NoticeReq;
import com.hurt.competition.admin.model.Notice;
import com.hurt.competition.admin.service.NoticeService;
import com.hurt.competition.common.exception.CoreException;
import com.hurt.competition.common.util.CoreResultBuilder;
import com.hurt.competition.common.vo.CoreResult;
import com.hurt.competition.common.vo.PageResult;
import com.hurt.competition.player.dto.SysUserReq;
import com.hurt.competition.player.model.SysUser;
import com.hurt.competition.player.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.crypto.digest.DigestUtil;

//选手端基础功能大概是注册账号，报名比赛，查看通知，上传作品（论文形式），查询成绩
//TODO:查看通知，上传作品（论文形式），查询成绩

@RestController
@RequestMapping("/player/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private NoticeService noticeService;

    //分页查询
    @PostMapping("/list")
    public CoreResult list(@RequestBody SysUserReq req){
        PageResult<SysUser> page = sysUserService.queryList(req);
        return CoreResultBuilder.success(page);
    }

    /**
     * 根据用户id查询详情
     * @param user
     * @return
     */
    @PostMapping("/info")
    public CoreResult info(@RequestBody SysUser user){
        // 检查用户是否已经存在
        if(user.getId() == null){
            return CoreResultBuilder.error("参数有误，请修改后重试");
        }

        SysUser resUser = sysUserService.queryInfo(user);
        return CoreResultBuilder.success(resUser);
    }

    //注册
    @PostMapping("/registry")
    public CoreResult registry(@RequestBody SysUser user){
        // 检查用户名是否已经存在
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName,user.getUserName());
        if (!CollectionUtils.isEmpty(sysUserService.list(queryWrapper))) {
            return CoreResultBuilder.error("该用户名已被注册");
        }

        // 检查密码是否符合要求（例如，长度、强度等）
        if (!isPasswordValid(user.getUserPwd())) {
            return null;
        }

        user.setUserPwd(userPwdSHA(user.getUserPwd()));

        // 将用户信息保存到数据库中
        sysUserService.insertOrUpdate(user);
        return CoreResultBuilder.success(user);
    }

    //密码具体要求
    private boolean isPasswordValid(String userPwd) {
        int minLength = 6; // 最小密码长度
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";//特殊字符

        //长度是否符合
        if (userPwd.length() < minLength) {
            throw new CoreException("密码不符合要求：长度应大于等于6");
        }

        //特殊字符是否包含
        if (!userPwd.matches(regex)){
            throw new CoreException("密码不符合要求：应同时包含大写、小写字母、特殊字符和数字");
        }
        return true;
    }

    public static String userPwdSHA(String userPwd) {
        userPwd = DigestUtil.sha256Hex(userPwd);
        return userPwd;
    }

    //登录
    @PostMapping("/login")
    public CoreResult login(@RequestBody SysUser user){
        // 验证用户名和密码是否合法
        if(StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getUserPwd())){
            return CoreResultBuilder.error("用户名或密码不能为空");
        }

        user.setUserPwd(userPwdSHA(user.getUserPwd()));

        //验证用户名和密码是否匹配
        SysUser loginUser = sysUserService.getUserByLogin(user);
        if(loginUser == null){
            return CoreResultBuilder.error("用户名或密码错误");
        }

        // 将用户信息保存到数据库中
        loginUser = sysUserService.getUserByLogin(user);
        return CoreResultBuilder.success(loginUser);
    }

    //查看通知
    @PostMapping("/resetPwd")
    public CoreResult resetPwd(@RequestBody SysUser user){
        if(StringUtils.isBlank(user.getUserPwd()) || user.getId() == null){
            return CoreResultBuilder.error("参数不能为空");
        }

        // 校验密码强度
        isPasswordValid(user.getUserPwd());

        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId,user.getId())
                .set(SysUser::getUserPwd,userPwdSHA(user.getUserPwd()));

        return CoreResultBuilder.success();
    }

    //查看通知
    @PostMapping("/checkNotice")
    public CoreResult checkNotice(@RequestBody NoticeReq req){
        PageResult<Notice> page = noticeService.queryList(req);
        return CoreResultBuilder.success(page);
    }


}